<template>
    <div class="app-mob-calendar ">
        <div v-if="show" :class="['calender_box' , activeItem]">
            <app-calendar
                ref="calendar"
                @prev="prev"
                @next="next"
                :value="value"
                :markDate="markDate"
                :responsive="true"
                :isChangeStyle ="true"
                :illustration="illustration"
                @select="clickDay"
                @selectYear="selectYear"
                @selectMonth="selectMonth"
                :sign="sign"
                :events="eventsDate"
                :tileContent="tileContent"></app-calendar>
            <ion-segment :value="activeItem" @ionChange="ionChange">
                <ion-segment-button value="activity2">
                    <ion-label>已结束活动</ion-label>
                </ion-segment-button>
                <ion-segment-button value="activity">
                    <ion-label>未进行活动</ion-label>
                </ion-segment-button>
            </ion-segment>
            <div class="calendar-events">
                <van-steps direction="vertical">
                    <van-step v-for="(i,index) in evendata[activeItem]" :key="index">
                        <p>{{i.time}}</p>
                        <div v-for="item in i.evens" :key="item.id" class="even-box">
                        <div v-if="activeItem == 'activity2'" >
                            <div class="evenname">{{item.activity_type_id_text}}</div>
                            <div class="evenname">{{item.res_name}}</div>
                            <div class="evenname">{{item.icon}}</div>
                        </div>
                        <div v-if="activeItem == 'activity'" >
                            <div class="evenname">{{item.activity_type_id_text}}</div>
                            <div class="evenname">{{item.res_name}}</div>
                            <div class="evenname">{{item.icon}}</div>
                        </div>
                        <ion-icon @click="remove([item])" class="event-delete" name="close-outline"></ion-icon>
                        </div>
                    </van-step>
                </van-steps>
            </div>
        </div>
    </div>
</template>


<script lang='ts'>
import { Vue, Component, Prop, Provide, Emit, Watch, Model } from 'vue-property-decorator';
import { CreateElement } from 'vue';
import { Subject, Subscription } from 'rxjs';
import { ControlInterface } from '@/interface/control';
import GlobalUiService from '@/global-ui-service/global-ui-service';
import Mail_activityService from '@/app-core/service/mail-activity/mail-activity-service';
import MobActivityCalendarService from '@/app-core/ctrl-service/mail-activity/mob-activity-calendar-calendar-service';

import moment from 'moment';


@Component({
    components: {
    }
})
export default class MobActivityCalendarBase extends Vue implements ControlInterface {

    /**
     * 名称
     *
     * @type {string}
     * @memberof MobActivityCalendar
     */
    @Prop() protected name?: string;

    /**
     * 视图通讯对象
     *
     * @type {Subject<ViewState>}
     * @memberof MobActivityCalendar
     */
    @Prop() protected viewState!: Subject<ViewState>;

    /**
     * 应用上下文
     *
     * @type {*}
     * @memberof MobActivityCalendar
     */
    @Prop({ default: {} }) protected context?: any;

    /**
     * 视图参数
     *
     * @type {*}
     * @memberof MobActivityCalendar
     */
    @Prop({ default: {} }) protected viewparams?: any;

    /**
     * 视图状态事件
     *
     * @protected
     * @type {(Subscription | undefined)}
     * @memberof MobActivityCalendar
     */
    protected viewStateEvent: Subscription | undefined;

    /**
     * 获取部件类型
     *
     * @returns {string}
     * @memberof MobActivityCalendar
     */
    protected getControlType(): string {
        return 'CALENDAR'
    }

    /**
     * 全局 ui 服务
     *
     * @private
     * @type {GlobalUiService}
     * @memberof MobActivityCalendar
     */
    private globaluiservice: GlobalUiService = new GlobalUiService();

    /**
     * 建构部件服务对象
     *
     * @type {MobActivityCalendarService}
     * @memberof MobActivityCalendar
     */
    protected service: MobActivityCalendarService = new MobActivityCalendarService();

    /**
     * 实体服务对象
     *
     * @type {Mail_activityService}
     * @memberof MobActivityCalendar
     */
    protected appEntityService: Mail_activityService = new Mail_activityService();
    

    /**
     * 关闭视图
     *
     * @param {any[]} args
     * @memberof MobActivityCalendar
     */
    protected closeView(args: any[]): void {
        let _this: any = this;
        _this.$emit('closeview', args);
    }


    /**
     * 显示处理提示
     *
     * @type {boolean}
     * @memberof MobActivityCalendar
     */
    @Prop({ default: true }) protected showBusyIndicator!: boolean;

    /**
     * 当前年份
     *
     * @type {string}
     * @memberof MobActivityCalendar
     */
    protected year: number = 0;

    /**
     * 当前月份(0~11)
     *
     * @type {string}
     * @memberof MobActivityCalendar
     */
    protected month: number = 0;

    /**
     * 开始时间
     *
     * @type {*}
     * @memberof MobActivityCalendar
     */
    protected start: any;

    /**
     * 标志数据
     * @type {Array<any>}
     * @memberof MobActivityCalendar
     */
    public sign: Array<any> = []
    
    /**
     * 结束时间
     *
     * @type {*}
     * @memberof MobActivityCalendar
     */
    protected end: any;

    /**
     * 当前日期
     * @type {*}
     * @memberof MobActivityCalendar
     */
    protected currentDate:any = new Date();

    /**
     * 当前天
     *
     * @type {string}
     * @memberof MobActivityCalendar
     */
    protected day: number = 0;

    /**
     * 标记数组
     *
     * @type {Array<any>}
     * @memberof MobActivityCalendar
     */
    protected markDate: Array<any> = [];

    /**
     * 事件时间
     *
     * @memberof MobActivityCalendar
     */
    public eventsDate :any = {};

    /**
     * 日历项集合对象
     *
     * @type {*}
     * @memberof MobActivityCalendar
     */
    public calendarItems: any = {};

    /**
     * 日历数据项模型
     *
     * @type {Map<string, any>}
     * @memberof MobActivityCalendar
     */
    public calendarItemsModel: Map<string, any> = new Map([
        [
            'activity2', {
                appde: 'mail_activity',
                keyPSAppDEField: 'id',
                majorPSAppDEField: 'display_name',
            }
        ],
        [
            'activity', {
                appde: 'mail_activity',
                keyPSAppDEField: 'id',
                majorPSAppDEField: 'display_name',
            }
        ],
    ]);

    /**
     * 日历显示状态
     *
     * @memberof MobActivityCalendar
     */
    public show = false;

    /**
     *  选中日期
     * 
     * @type {Array<any>}
     * @memberof MobActivityCalendar
     */
    protected tileContent: Array<any> = [];

    /**
     *  默认选中
     * 
     * @type {Array<any>}
     * @memberof MobActivityCalendar
     */
    protected value: Array<any> = [];

    /**
     *  日历样式
     * 
     * @type {Array<any>} 
     * @memberof MobActivityCalendar
     */
    protected calendarStyle: string = 'month_timeline';

    /**
     * 获取多项数据
     *
     * @returns {any[]}
     * @memberof MobActivityCalendar
     */
    public getDatas(): any[] {
      return [];
    }
    
    /**
     * 时间轴加载条数
     *
     * @type {number}
     * @memberof MobActivityCalendar
     */  
    public count :number = 20;

    /**
     * 获取单项树
     *
     * @returns {*}
     * @memberof MobActivityCalendar
     */
    public getData(): any {
      return {};
    }

    /**
     * vue生命周期created
     *
     * @memberof MobActivityCalendar
     */
    protected created() {
      this.afterCreated();
    }

    /**
     * 处理created之后的逻辑
     *
     * @memberof MobActivityCalendar
     */
    protected afterCreated() {
        this.initcurrentTime();
        if (this.viewState) {
            this.viewState.subscribe(({ tag, action, data }) => {
                if (!Object.is(this.name, tag)) {
                    return;
                }
                if (Object.is(action, "load")) {
                    this.formatData(this.currentDate, data);
                }
            });
        }
    }

    /**
     * 事件绘制数据
     *
     * @memberof MobActivityCalendar
     */
    public evendata :any = {activity2:[],activity:[],}

    /**
     * 图标信息
     *
     * @memberof MobActivityCalendar
     */
    public illustration = [{color:"red",text:"已结束活动"},{color:"blue",text:"未进行活动"},]
    /**
     * 激活项
     *
     * @type {string}
     * @memberof MobActivityCalendar
     */
    protected activeItem: string = 'activity2';

    /**
     * 分页节点切换
     *
     * @param {*} $event
     * @returns
     * @memberof MobActivityCalendar
     */
    protected ionChange($event:any) {
        let { detail: _detail } = $event;
        if (!_detail) {
            return ;
        }
        let { value: _value } = _detail;
        if (!_value) {
            return ;
        }
        this.activeItem = _value;
        this.formatData(new Date(this.year+'/'+(this.month+1)+'/'+this.day));
    }

    /**
     * 查询天数
     *
     * @memberof MobActivityCalendar
     */
    protected selectday(year: any, month: any, weekIndex: any) {
        this.value = [year, month, this.day];
    }

    /**
     * 上一月事件的回调方法
     *
     * @memberof MobActivityCalendar
     */
    protected prev(year: any, month: any, weekIndex: any) {
        if(this.calendarStyle == "month_timeline" || this.calendarStyle == "month"){
            this.selectday(year, month, this.day);
            this.formatData(new Date(year+'/'+month+'/'+'1'));
        }
        if(this.calendarStyle == "week_timeline" || this.calendarStyle == "week"){
            this.countWeeks(year,month,weekIndex);
        }
    }

    /**
     * 下一月事件的回调方法
     *
     * @memberof MobActivityCalendar
     */
    protected next(year: any, month: any, weekIndex: any) {
        if(this.calendarStyle == "month_timeline" || this.calendarStyle == "month" ){
            this.selectday(year, month, this.day);
            this.formatData(new Date(year+'/'+month+'/'+'1'));
        }
        if(this.calendarStyle == "week_timeline" || this.calendarStyle == "week"){
            this.countWeeks(year,month,weekIndex);
        }
    }

    /**
     * 删除
     *
     * @param {any[]} datas
     * @returns {Promise<any>}
     * @memberof MobActivityCalendar
     */
    public async remove(datas: any[]): Promise<any> {
        const calendarItemModel: any = this.calendarItemsModel.get(this.activeItem);
        let { appde, keyPSAppDEField, majorPSAppDEField }: { appde: string, keyPSAppDEField: string, majorPSAppDEField: string } = calendarItemModel;
        let arg: any = {};
        let keys: Array<string> = [];
        let infoStr: string = '';
        datas.forEach((data: any, index: number) => {
            keys.push(data[keyPSAppDEField]);
            if (index < 5) {
                if (!Object.is(infoStr, '')) {
                    infoStr += '、';
                }
                infoStr += data[majorPSAppDEField];
            }
        });

        if (datas.length < 5) {
            infoStr = infoStr + ' 共' + datas.length + '条数据';
        } else {
            infoStr = infoStr + '...' + ' 共' + datas.length + '条数据';
        }
        return new Promise((resolve, reject) => {
            const _remove = async () => {
                let _context: any = { [appde]: keys.join(';') }
                const response: any = await this.service.delete(this.activeItem, { ...this.context, ..._context }, arg, this.showBusyIndicator);
                if (response && response.status === 200) {
                    this.$notice.success('删除成功');
                    this.formatData(this.currentDate);
                    resolve(response);
                } else {
                    const { error: _data } = response;
                    this.$notice.error(_data.message);
                    reject(response);
                }
            }

            this.$dialog.confirm({
                title: '警告',
                message: '确认要删除 ' + infoStr + '，删除操作将不可恢复？',
            }).then(() => {
                _remove();
            }).catch(() => {
            });
        });
    }

    /**
     * 选择年份事件的回调方法
     *
     * @memberof MobActivityCalendar
     */
    protected selectYear(year: any) {
      this.value = [year, this.month, this.day];
      this.formatData(new Date(year+'/'+this.month+'/'+this.day));
    }

    /**
     * 选择月份事件的回调方法
     *
     * @memberof MobActivityCalendar
     */
    protected selectMonth(month: any, year: any) {
      this.selectday(year, month, this.day);
      this.formatData(new Date(year+'/'+month+'/'+this.day));
    }

    /**
     * 初始化当前时间
     *
     * @memberof MobActivityCalendar
     */
    protected initcurrentTime() {
      let tempTime = new Date();
      this.year = tempTime.getFullYear();
      this.month = tempTime.getMonth();
      this.day = tempTime.getDate();
    }

    /**
     * 格式化数据
     *
     * @memberof MobActivityCalendar
     */
    protected formatData(curtime:any,data: any = {}) {
        this.currentDate = curtime;
        this.year = curtime.getFullYear();
        this.month = curtime.getMonth();
        this.day = curtime.getDate();
        this.start = (moment as any)(curtime).startOf('month').format('YYYY-MM-DD HH:mm:ss');
        this.end = (moment as any)(curtime).endOf('month').format('YYYY-MM-DD HH:mm:ss');
        this.load(Object.assign(data, {
          "start": this.start,
          "end": this.end
        }));
    }

    /**
     * 数据加载
     *
     * @protected
     * @param {*} [opt={}]
     * @returns {Promise<any>}
     * @memberof MobActivityCalendar
     */
    protected async load(opt: any = {}): Promise<any> {
        const arg: any = { ...opt };
        const isloading: boolean = this.showBusyIndicator === true ? true : false;
        const response: any = await this.service.search(this.activeItem, { ...this.context }, { ...arg }, this.showBusyIndicator);
        if (response && response.status === 200) {
            this.calendarItems = response.data;
            this.setTileContent();
        } else {
            this.$notice.error('系统异常，请重试!');
        }
        this.show = true;
    }

    

    /**
     * 设置事件数组
     *
     * @protected
     * @memberof MobActivityCalendar
     */
    protected setTileContent(){
        this.evendata = {activity2:[],activity:[],}
        let activity2Item :Array<any> = this.parsingData('activity2','create_date');
        let activityItem :Array<any> = this.parsingData('activity','create_date');
        this.setSign(activity2Item,activityItem,);
    }

    /**
     * 格式化标志数据
     * 
     * @param any 
     * @memberof MobActivityCalendar
     */
    public setSign(activity2Item: any,activityItem: any,){
      let signData = [...activity2Item,...activityItem,];
      let obj: any = {}
      // 格式化数据
      signData.forEach((item:any,index:number) => {
          if(item.time.length == 10){
            let year = item.time.split('-')[0];
            let month = item.time.split('-')[1];
            let day = item.time.split('-')[2];
            if( month < 10 ){
              month = month.replace('0','')
            }
            if(day < 10){
              day = day.replace('0','')
            }
            item.time = year+'-'+month+'-'+day;
          }
          if(!obj[item.time]){
            Object.assign(obj,{[item.time]:item.evens})
          }else{
            Object.assign(obj,{[item.time]:[...obj[item.time],...item.evens]})
          }
      });
      for (const key in obj) {
        this.sign.push({time:key,evens:obj[key]});
      }
    }

    /**
     * 解析日历事件数据
     *
     * @protected
     * @memberof MobActivityCalendar
     */
    public parsingData(tag:string,mark:string) :Array<any>{
      let dataItem :any = [];
        if(this.calendarItems[tag]){
            this.calendarItems[tag].forEach((item:any) => {
                if(dataItem.length == 0){
                  dataItem.push({time:item[mark].substring(0, 10),evens:[item]});
                }else{
                  dataItem.forEach((sig:any)=>{
                    if(sig.time.substring(0, 10) != item[mark].substring(0, 10)){
                      dataItem.push({time:item[mark].substring(0, 10),evens:[item]});
                    }
                })}
                if(item[mark]){
                  if (this.evendata[tag].length > 0) {
                    this.evendata[tag].forEach((i: any) => {
                      if (i.time === item[mark].substring(0, 10)) {
                        if (i.evens) {
                          i.evens.push(item);
                        }
                      } else {
                        this.evendata[tag].push({
                          time: item[mark].substring(0, 10),
                          evens: [item]
                        });
                      }
                    });
                  } else {
                    this.evendata[tag].push({
                      time: item[mark].substring(0, 10),
                      evens: [item]
                    });
                  }
                }
            });
        }
        return dataItem;
    }

    /**
     * 日历部件数据选择日期回调
     *
     * @param any 
     * @memberof MobActivityCalendar
     */
    protected clickDay(data: any) {
      if (data) {
        let temptime = new Date(data);
        this.year = temptime.getFullYear();
        this.month = temptime.getMonth();
        this.day = temptime.getDate();
        this.start = (moment as any)(temptime).startOf('day').format('YYYY-MM-DD HH:mm:ss');
        this.end = (moment as any)(temptime).endOf('day').format('YYYY-MM-DD HH:mm:ss');
        this.load(Object.assign(this.viewparams, { "start": this.start, "end": this.end }));
      }
    }

    /**
     * 日程点击事件
     *
     * @param {*} $event 事件信息
     * @memberof MobActivityCalendar
     */
    protected getEditView(deName: string) {
        let view: any = {};
        switch(deName){
            case "mail_activity": 
                view = {
                    viewname: 'mail-activity-mob-edit-view', 
                    height: 0, 
                    width: 0,  
                    title: '活动移动端编辑视图', 
                    placement: '',
                    deResParameters: [],
                    parameters: [{ pathName: 'mail_activities', parameterName: 'mail_activity' }, { pathName: 'mobeditview', parameterName: 'mobeditview' } ],
                };
                break;
        }
        return view;
    }

    /**
     * 日程点击事件
     *
     * @param {*} $event 事件信息
     * @memberof MobActivityCalendar
     */
    protected async onEventClick($event: any): Promise<any> {
        let view: any = {};
        let _context: any = Object.assign({},this.context);
        let itemType = $event.itemType;
        switch(itemType) {
            case "Activity2":
                _context.mail_activity = $event.mail_activity;
                view = this.getEditView("mail_activity");
                break;
            case "Activity":
                _context.mail_activity = $event.mail_activity;
                view = this.getEditView("mail_activity");
                break;
        }
        if (Object.is(view.placement, 'INDEXVIEWTAB') || Object.is(view.placement, '')) {
            const routePath = this.$viewTool.buildUpRoutePath(this.$route, this.context, view.deResParameters, view.parameters, [JSON.parse(JSON.stringify(_context))] , JSON.parse(JSON.stringify(this.viewparams)));
            this.$router.push(routePath);
        } else {
            let container: Subject<any> = new Subject();
            if (Object.is(view.placement, 'POPUPMODAL')) {
                container = await this.$appmodal.openModal(view,  JSON.parse(JSON.stringify(_context)),  JSON.parse(JSON.stringify(this.viewparams)));
            } else if (view.placement.startsWith('DRAWER')) {
                container = this.$appdrawer.openDrawer(view,  JSON.parse(JSON.stringify(_context)),  JSON.parse(JSON.stringify(this.viewparams)));
            }
            container.subscribe((result: any) => {
                if (!result || !Object.is(result.ret, 'OK')) {
                    return;
                }
                // 刷新日历
                this.load(Object.assign(this.viewparams, { "start": this.start, "end": this.end }));
            });
        }
    }
    /**
     * 根据周下标计算事件
     *
     * @param {*} $event 事件信息
     * @memberof MobActivityCalendar
     */
    public countWeeks(year: any, month: any, week: any) {
        let date = new Date(year + '/' + month + '/' + 1);
        let weekline = date.getDay();
        if(weekline == 0){
          this.formatData(new Date(year + '/' + month + '/' + (week*7 +1)));
        }else{
          this.formatData(new Date(year + '/' + month + '/' + (week*7 - weekline + 1)));
        }
    }
}
</script>

<style lang='less'>
@import './mob-activity-calendar-calendar.less';
</style>